package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;

import csc.daonjpa.java.controller.EntityManagerFactoryUtil;
import csc.daonjpa.java.domain.Account;

/**
 * DAO class for Account entity. This class contains all methods that inserts/updates/deletes
 * account info
 * @author nvu3
 *
 */
@Component
public class AccountDAO {
	
	/**
	 * @return all accounts from Account table
	 */
	public List<Account> getAccounts(String loginId) {
		
		// Obtains entity manager object
		EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();
		
		// Obtains transaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();
		
		// -----------Begin transaction-----------
		List<Account> listAccount = null;
		try {
			entr.begin();
			// Get a list of accounts from DB
			TypedQuery<Account> query = entityManager.createQuery("SELECT a FROM Account a WHERE a.loginId=:login_Id", Account.class);
			listAccount = query.setParameter("login_Id", loginId).getResultList();
			entr.commit();
		} catch (Exception e) {
			e.getStackTrace();
			entityManager.close();
		}
		// -----------End transaction-----------

		return listAccount;
		
	}
	
	/**
	 * Add account to Account table
	 * @param account Account entity that contains mapped with each column in Account table
	 * @return
	 */
	public boolean addAccount(Account account) {
		// Obtains entity manager object
		EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();
		
		// Obtains transaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();
		
		try {
			// -----------Begin transaction-----------
			entr.begin();
			// Insert a row to Account table
			entityManager.persist(account);
			entr.commit();
		} catch (Exception e) {
			entityManager.close();
		}
		// -----------End transaction-----------
		
		return true;
	}
}
